﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace RandomViewFromListing
{
    public partial class MasterView : Form
    {
        private string imageListFile;
        
        //private string favoriteFile = @"fav.txt";
        private StreamWriter sw;
        private List<string> MyimageList = new List<string>();
        private int index = 0;
        Random generator = new Random();
        private List<string> FavList = new List<string>();
        int initialCount;
        int markedCount = 0;
        int removedCount = 0;
        int difference = 0;

        public MasterView()
        {
            InitializeComponent();
        }

        private void MasterView_Load(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            imageListFile = openFileDialog1.FileName;


            // Open the file to read from.
            using (StreamReader sr = File.OpenText(imageListFile))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    // load the List of image pathnames
                    MyimageList.Add(s);
                }
            }
            
            
            countLabel.Text = MyimageList.Count.ToString();

            // there are no back images so disable functionality
            backButton.Enabled = false;
            
            initialCount = MyimageList.Count;
            
            initialItemsLabel.Text = initialCount.ToString();
            
            // set values of other metric labels
            CalculateDifference();
       

        }


        /*
         * Source from: 
         * http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/f3e2d7ba-ff1f-472e-9a26-70f7918e7aac/
         */

        private void RenderImage(string path)
        {

            // for RenderImage
            
            Size scaledImageSize;
            
            // current and desired sizes
            int cx;
            int cy;
            int dx;
            int dy;


            Image tempImage = Image.FromFile(path);

            cy = tempImage.Height;
            cx = tempImage.Width;
            dy = pictureBox1.Height;
            dx = pictureBox1.Width;


            scaledImageSize = SetScaleMultiplier(cx, cy, dx, dy);
            Bitmap imgOutput = new Bitmap(
                tempImage, scaledImageSize.Width, scaledImageSize.Height);

            // Stretches the image to fit the pictureBox.
            pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;

            pictureBox1.Image = (Image)imgOutput;
        }




        
        private Size SetScaleMultiplier(
            int currentImageWidth,
            int currentImageHeight,
            int desiredImageWidth,
            int desiredImageHeight)
        {

            double scaleImageMultiplier = 0;

            /* Determine if Image is Portrait or Landscape. */
            if (currentImageHeight > currentImageWidth)    /* Image is Portrait */
            {
                /* Calculate the multiplier based on the heights. */
                if (desiredImageHeight > desiredImageWidth)
                {
                    scaleImageMultiplier = (double)desiredImageWidth / (double)currentImageWidth;
                }

                else
                {
                    scaleImageMultiplier = (double)desiredImageHeight / (double)currentImageHeight;
                }
            }

            else /* Image is Landscape */
            {
                /* Calculate the multiplier based on the widths. */
                if (desiredImageHeight >= desiredImageWidth)
                {
                    scaleImageMultiplier = (double)desiredImageWidth / (double)currentImageWidth;
                }

                else
                {
                    scaleImageMultiplier = (double)desiredImageHeight / (double)currentImageHeight;
                }
            }

            return new Size(
                (int)(currentImageWidth * scaleImageMultiplier),
                (int)(currentImageHeight * scaleImageMultiplier));

        }// end SetScaleMultiplier

        
        // next button is pressed
        private void nextButton_Click(object sender, EventArgs e)
        {
            
            
            // You press the next button and prev becomes enabled
            index++;
            backButton.Enabled = true;
            indexLabel.Text = index.ToString();

            
            // check to see if at end of records
            if (index == MyimageList.Count - 1)
            {
                //button1.Enabled = true;
                nextButton.Enabled = false;
            }
            else
                nextButton.Enabled = true;

            RenderImage(MyimageList[index]);
            fileLinkLabel.Text = MyimageList[index];

           
        }


        private void CheckForEmptyList()
        {
            if (MyimageList.Count == 1)
            {
                MessageBox.Show("End of Images!");
                nextButton.Enabled = false;
                backButton.Enabled = false;
                button1.Enabled = false;
            }
        }


        private void backButton_Click(object sender, EventArgs e)
        {
            // if button 1 (prev) is pressed then it has been enabled
            index--;
            indexLabel.Text = index.ToString();
            

            // check to see if you are at beginning
            if (index == 0)
            {
                backButton.Enabled = false;
                nextButton.Enabled = true;
            }
            else
                backButton.Enabled = true;

            RenderImage(MyimageList[index]);
            fileLinkLabel.Text = MyimageList[index];
        }

        // issue with back and next due to index not being updated
        // if next was disabled and a random index in the middle is
        // chosen then next should be enabled, this doesn't happen.
        private void favButton_Click(object sender, EventArgs e)
        {
            //sw.WriteLine(MyimageList[index]);
            FavList.Add(MyimageList[index]);
            MyimageList.RemoveAt(index);
            MyimageList.TrimExcess();
            countLabel.Text = MyimageList.Count.ToString();
            SetRandomImage();
            CheckForEmptyList();
            markedCount++;
            CalculateDifference();
            
        }

        // same state issue with back button as next button.
        private void removeButton_Click(object sender, EventArgs e)
        {
            MyimageList.RemoveAt(index);
            MyimageList.TrimExcess();
            countLabel.Text = MyimageList.Count.ToString();
            SetRandomImage();
            CheckForEmptyList();
            removedCount++;
            CalculateDifference();

        }

        // random image button
        private void button1_Click(object sender, EventArgs e)
        {
            SetRandomImage();  
        }

        private void SetRandomImage()
        {
            index = generator.Next((MyimageList.Count));
            RenderImage(MyimageList[index]);
            fileLinkLabel.Text = MyimageList[index];
            indexLabel.Text = index.ToString();
        }



        private void MasterView_FormClosing(object sender, FormClosingEventArgs e)
        {
            
            
            // write favorites if you aren't working with the
            // favorite file!
            if (imageListFile != "fav.txt")
            {
                string toFav = Path.GetDirectoryName(imageListFile);

                string favoriteFile = toFav + "\\fav.txt";
                if (!File.Exists(favoriteFile))
                {
                    sw = File.CreateText(favoriteFile);
                }
                else
                {
                    sw = File.AppendText(favoriteFile);
                }

                foreach (string s in FavList)
                {
                    sw.WriteLine(s);
                }


            }
            else
            {
                string toFav = Path.GetDirectoryName(imageListFile);
                string favoriteFile = toFav + "\\fav" + DateTime.Now.Ticks.ToString() + ".txt";
                if (!File.Exists(favoriteFile))
                {
                    sw = File.CreateText(favoriteFile);
                }
                else
                {
                    sw = File.AppendText(favoriteFile);
                }

                foreach (string s in FavList)
                {
                    sw.WriteLine(s);
                }

            }

            sw.Close();




            StreamWriter rewriter;
            if (!File.Exists(imageListFile))
            {
                rewriter = File.CreateText(imageListFile);
            }
            else
            {
                rewriter = new StreamWriter(imageListFile);
            }

            foreach (string img in MyimageList)
            {
                rewriter.WriteLine(img);
            }
            rewriter.Close();
            
        }

        // output difference to labels. really just visual debugging for now.
        private void CalculateDifference()
        {
            markedLabel.Text = markedCount.ToString();
            removedLabel.Text = removedCount.ToString();
            difference = initialCount - (markedCount + removedCount);
            differenceLabel.Text = difference.ToString();
        }

        private void fileLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(fileLinkLabel.Text);
        }

    }
}
